<template>
  <div id="applyVSReport">
    <Breadcrumb content="申请项目和报告项目对照" />
    <div class="bodyContent">
      <Splitpanes class="area">
        <!-- 左侧报告单元列表 -->
        <Pane :size="30">
          <vxe-toolbar perfect>
            <template #buttons>
              <div class="smallToolTitle">报告单元</div>
              <SelectWorkGroup :url="'/api/rptGroup/findRptGroupList'" :businessType="'10'" @getSelectedId="getSelectedId"></SelectWorkGroup>

              <vxe-input v-model="searchForm.groupSearchValue" type="search" clearable class="vxeInputSearch" placeholder="关键字查询" @clear="getFeeItemList" @keyup="keyupFeeItemEnter" @search-click="getFeeItemList()"></vxe-input>
              <vxe-button type="text" class="button-blue" icon="vxe-icon-refresh" content="刷新" :loading="feeItemShowLoading" @click="getFeeItemList"></vxe-button>
            </template>
          </vxe-toolbar>
          <div class="leftTable">
            <vxe-table ref="labFeeItemTable" border class="mytable-scrollbar" height="auto" show-header-overflow show-overflow align="left" :row-config="{ isCurrent: true, isHover: true }" @current-change="grouprowClick" :data="feeItemList" :loading="feeItemShowLoading">
              <vxe-column type="seq" title="#" width="30"></vxe-column>
              <vxe-column field="feeType" title="类型" width="80">
                <template #default="{ row }">
                  <span>{{ getFeeTypeDesc(row) }}</span>
                </template>
              </vxe-column>
              <vxe-column field="feeCode" title="项目编号" width="80"></vxe-column>
              <vxe-column field="feeName" title="项目名称" width="140"></vxe-column>
              <vxe-column field="feeiVsDictCnt" title="项目数"></vxe-column>
            </vxe-table>
          </div>
        </Pane>
        <!-- 中间对照信息 -->
        <Pane :size="36">
          <vxe-toolbar perfect>
            <template #buttons>
              <!-- <vxe-input
                v-model="searchValueVS"
                type="search"
                clearable
                class="vxeInputSearch"
                placeholder="关键字查询"
                @clear="getReportGroupList"
                @keyup="getReportGroupList"
                @search-click="getReportGroupList()"
              ></vxe-input>-->
              <vxe-button type="text" class="button-blue" icon="vxe-icon-refresh" content="刷新" :loading="showLoading" @click="findItemDictList"></vxe-button>
              <vxe-button type="text" class="button-blue" icon="vxe-icon-save" content="复制" @click="copyFeeitemVsItemDict"></vxe-button>
              <vxe-button type="text" class="button-blue" icon="vxe-icon-save" content="粘贴" @click="pasteFeeitemVsItemDict" :disabled="copyfeeVsDictList.length<=0"></vxe-button>
              <vxe-button type="text" class="button-blue" icon="vxe-icon-save" content="保存" @click="saveFeeitemVsItemDictList"></vxe-button>
            </template>
          </vxe-toolbar>

          <div class="leftTable">
            <vxe-table ref="feeitemVsItemdictTable" border class="mytable-scrollbar" height="auto" show-header-overflow show-overflow align="left" :row-config="{ isCurrent: true, isHover: true }" :data="feeitemVsItemdictList" :loading="showLoading" @cell-dblclick="deleteFeeitemVsItemdictList" :edit-config="{ trigger: 'click', mode: 'cell' }" :column-config="{ resizable: true }">
              <!-- <vxe-column type="checkbox" width="30px" align="center"></vxe-column> -->
              <vxe-column type="seq" title="序号" width="50"></vxe-column>
              <vxe-column field="itemNa" title="对应报告项目"></vxe-column>
              <vxe-column field="isOptional" title="是否可选">
                <template #default="{ row }">
                  <!-- 是否删改 开关 -->
                  <vxe-switch v-model="row.isOptional" open-label="是" close-label="否" open-value="0" close-value="1"></vxe-switch>
                </template>
              </vxe-column>
              <vxe-column :field="colitem.instrCode" :title="colitem.instrName" v-for="(colitem, index) in instrSetupList" :key="index" :edit-render="{ autofocus: '.vxe-input--inner' }">
                <template #default="{ row }">
                  <span>{{ row[colitem.instrCode] }}</span>
                </template>
                <!-- <template #default="{ row, rowIndex }">
                  <vxe-button mode="text" @click="updateChannel(rowIndex,colitem.instrCode)">{{ row[colitem.instrCode] }}</vxe-button>
                </template> -->
                <template #edit="{ row, rowIndex }">
                  <vxe-input @focus="updateChannel(rowIndex, colitem.instrCode)" v-model="row[colitem.instrCode]" type="text" placeholder="请输入昵称"></vxe-input>
                </template>
              </vxe-column>
              <!--              <vxe-column field="externalCodeOne" title="外部代码一"></vxe-column>
              <vxe-column field="externalCodeTwo" title="外部代码二"></vxe-column>
              <vxe-column field="externalCodeThree" title="外部代码三"></vxe-column>-->
            </vxe-table>
          </div>
        </Pane>
        <!-- 右侧信息 -->
        <Pane :size="34">
          <vxe-toolbar perfect>
            <template #buttons>
              <vxe-input v-model="searchValue" type="search" clearable class="vxeInputSearch" placeholder="关键字查询" @clear="getItemDictList" @keyup="keyupItemDictEnter" @search-click="getItemDictList()"></vxe-input>
              <vxe-button type="text" class="button-blue" icon="vxe-icon-refresh" content="刷新" :loading="showLoading" @click="getItemDictList"></vxe-button>
            </template>
          </vxe-toolbar>
          <div class="rightTable">
            <vxe-table ref="itemDictTable" border show-header-overflow height="auto" show-overflow align="left" :row-config="{ isCurrent: true, isHover: true }" @cell-dblclick="itemDictRowClick" :data="itemDictList" :loading="showLoading" class="mytable-scrollbar">
              <vxe-column type="seq" title="#" width="30"></vxe-column>
              <vxe-column field="itemNo" title="项目代码" width="60" :edit-render="{ autofocus: '.vxe-input--inner' }">
                <template #edit="{ row }">
                  <vxe-input v-model="row.itemNo" clearable placeholder="关键字查询"></vxe-input>
                </template>
              </vxe-column>
              <vxe-column field="itemNa" title="报告项目名称" min-width="160px" :edit-render="{ autofocus: '.vxe-input--inner' }">
                <template #edit="{ row }">
                  <vxe-input v-model="row.itemNa" clearable placeholder="关键字查询"></vxe-input>
                </template>
              </vxe-column>
              <vxe-column field="rptGroupName" title="报告单元" width="160px" :edit-render="{ autofocus: '.vxe-input--inner' }">
                <template #edit="{ row }">
                  <vxe-input v-model="row.rptGroupName" clearable placeholder="关键字查询"></vxe-input>
                </template>
              </vxe-column>
              <vxe-column field="itemEnCode" title="英文缩写" width="90px" :edit-render="{ autofocus: '.vxe-input--inner' }">
                <template #edit="{ row }">
                  <vxe-input v-model="row.shortName" type="text"></vxe-input>
                </template>
              </vxe-column>
              <vxe-column field="itemClass" title="项目归类" width="100px">
                <template #default="{ row }">
                  <span>{{ formatCommon(itemClassDict, row.itemClass) }}</span>
                </template>
              </vxe-column>
              <vxe-column field="instrClass" title="仪器大类" width="100px">
                <template #default="{ row }">
                  <span>{{ formatCommon(instrClassDict, row.instrClass) }}</span>
                </template>
              </vxe-column>
              <vxe-column field="id" title="项目ID" width="60px" :edit-render="{ autofocus: '.vxe-input--inner' }">
                <template #edit="{ row }">
                  <vxe-input v-model="row.id" clearable placeholder="关键字查询"></vxe-input>
                </template>
              </vxe-column>
            </vxe-table>
          </div>
          <vxe-pager align="left" min-height="32px" height="32px" :current-page.sync="page.currentPage" :page-size.sync="page.pageSize" :total="page.totalResult" :layouts="['PrevJump', 'PrevPage', 'Number', 'NextPage', 'NextJump', 'Sizes', 'FullJump', 'Total']" @page-change="handleSizeChange($event)"></vxe-pager>
        </Pane>
      </Splitpanes>

      <el-dialog title="选择通道号" width="700px" :show-close="false" :draggable="true" v-model="addDialog" :append-to-body="true" :close-on-click-modal="false" class="interfacesetDialogAdd">
        <div class="tableBody" style="height: 600px">
          <vxe-table ref="labchannelTableRef" class="mytable-scrollbar dialogTable" border height="520px" align="center" :data="channelList" :loading="loading" :row-config="{ isCurrent: true, isHover: true }" :column-config="{ resizable: true }" @cell-dblclick="rptRowClick" resizable show-overflow keep-source>
            <vxe-column type="seq" title="序号" width="50"></vxe-column>
            <vxe-column field="channelCode" title="通道号"></vxe-column>
            <vxe-column field="itemDictName" title="对应报告项目"></vxe-column>
          </vxe-table>
        </div>
        <div class="dialog-footer flex justify-end">
          <el-button @click="closeAddDialog()">取消</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script lang="ts" setup>
// 引入组件区 ==========
import Breadcrumb from '@/components/Breadcrumb.vue';
import { Splitpanes, Pane } from 'splitpanes';
import { ref, reactive, getCurrentInstance, onMounted } from 'vue';
import { VxeMessage, VxeNotifyType } from '@/utils/CommonMessage'; //提示信息
import { AppStore } from '@/stores/store';
import { isEmpty } from 'lodash';
import SelectWorkGroup from '@/views/lab_sys/lab_bus/components/SelectWorkGroup.vue'; //报告单元引入下拉组件
import { GetRptGroupOptions } from '@/utils/SysOptionsHelper';
import { IsEmpty } from '@/utils/common';

let store = AppStore();
// 全局变量定义区 ==========
// 变量定义区
let { proxy }: any = getCurrentInstance();
let conWidth = ref(document.documentElement.clientWidth);
const itemDictList = reactive([]);
let selevctFeeItemRow: any = reactive({
  id: ''
});

let searchGroupForm = reactive({
  rptGroup: ''
});

let feeItemList = reactive([]);
let showLoading = ref(false); //刷新+表格加载
let feeItemShowLoading = ref(false);
let searchValue = ref('');
let searchValueVS = ref('');
const searchForm = reactive({
  orgId: store.userInfo.orgId,
  groupSearchValue: '',
  name: store.userInfo.orgName
});
const itemClassDict = reactive([]); //项目类型字典
const instrClassDict = reactive([]); //仪器大类字典
const itemKindDict = reactive([]); //结果类型字典
let instrSetupList = reactive([]); //仪器列表
let channelList = reactive([]); //通道号列表
let dataIndex = ref(null); //数据索引
let addDialog = ref(false); //添加弹框展示状态
let loading = ref(false); //添加弹框展示状态
let rowData = ref({}); //当前行数据

// 条数/页
const PageSizeList = [10, 50, 100, 200, 500];
// 分页
let page = reactive({
  currentPage: 1,
  pageSize: PageSizeList[1],
  totalResult: 0
});

const feeitemVsItemdictList: any = reactive([]);
let dictTreeTypeCodes: any = reactive(['reportCategory', 'YQDL', 'LABITEMKIND']);

// 方法定义区 =============
onMounted(() => {
  getDictItemsList();
});

//批量获取字典
async function getDictItemsList() {
  const codes = dictTreeTypeCodes.join(',');
  const url = '/api/sys/basDictDetail/findDictDetailListByDictCodes';
  const dictTreeTypeItems: any = await proxy.$http.get(url, { params: { code: codes } });
  const itemClassType = dictTreeTypeItems.data.find((item) => item.code === 'reportCategory');
  itemClassDict.push(...itemClassType.detailDataList);
  const instrClassType = dictTreeTypeItems.data.find((item) => item.code === 'YQDL');
  instrClassDict.push(...instrClassType.detailDataList);
  const itemKindType = dictTreeTypeItems.data.find((item) => item.code === 'LABITEMKIND');
  itemKindDict.push(...itemKindType.detailDataList);
}

//通过报告单元获取仪器信息
function getInstrList() {
  instrSetupList.length = 0;
  if (IsEmpty(searchGroupForm.rptGroup)) {
    return;
  }
  const url = '/lis/instrSetup/findLabInstrSetupList';
  proxy.$http
    .get(url, { params: { rptGroupId: searchGroupForm.rptGroup } })
    .then((res: any) => {
      if (res.status.code === 1) {
        instrSetupList.push(...res.data);
      }
    })
    .catch((err: any) => {
      proxy.$alert(err, '提示');
    });
}

function updateChannel(index, instrCode) {
  if (!IsEmpty(index)) {
    dataIndex.value = index;
  } else {
    dataIndex.value = null;
    return;
  }
  let itemNo = feeitemVsItemdictList[dataIndex.value].itemNo;

  addDialog.value = true;
  findChannelList(itemNo, instrCode);
}

function findChannelList(itemNo, instrCode) {
  loading.value = true;
  channelList.length = 0;
  if (IsEmpty(searchGroupForm.rptGroup)) {
    return;
  }
  loading.value = true;
  const url = '/lab/channel/findChannelList';
  proxy.$http
    .get(url, { params: { itemNo: itemNo, instrCode: instrCode, rptGroup: searchGroupForm.rptGroup } })
    .then((res: any) => {
      if (res.status.code === 200) {
        channelList.push(...res.data);
      }
      loading.value = false;
    })
    .catch((err: any) => {
      proxy.$alert(err, '提示');
      loading.value = false;
    });
}
//关闭窗口
function closeAddDialog() {
  addDialog.value = false;
}

// 点击当前行// 行点击事件
function rptRowClick({ row }: any) {
  const $reportTable = proxy.$refs.labchannelTableRef;
  if ($reportTable) {
    $reportTable.setCurrentRow(row);
  }

  updateChannelOpen(row);
  addDialog.value = false;
  findItemDictList();
}
//设置通通道号为双向
function updateChannelOpen(row) {
  proxy.$http
    .post('/lab/channel/editLabChannelOpen', row)
    .then((res: any) => {
      if (res.status.code === 1) {
        VxeMessage('修改成功', VxeNotifyType.success);
      } else {
        return;
      }
    })
    .catch((err: any) => {
      VxeMessage('修改异常', VxeNotifyType.error);
    });
}

function formatCommon(arr, value) {
  for (const item of arr) {
    if (item.code == value) {
      return item.name;
    }
  }
}

function getFeeTypeDesc(row) {
  let feeTypeDesc = '';
  const feeiVsDictCnt = row.feeiVsDictCnt;
  if (feeiVsDictCnt > 0) {
    feeTypeDesc = '已对照';
  } else {
    feeTypeDesc = '已关联';
  }
  return feeTypeDesc;
}

function getItemDictList() {
  page.currentPage = 1;
  findDictItemByFeeItemId(selevctFeeItemRow);
}

// 回车查询
function keyupFeeItemEnter(e: any) {
  if (e.$event.code == 'Enter') {
    getFeeItemList();
  }
}

function keyupItemDictEnter(e: any) {
  if (e.$event.code == 'Enter') {
    getItemDictList();
  }
}

// 获取申请项目
function getFeeItemList() {
  feeItemList.length = 0;
  feeItemShowLoading.value = true;
  const url = '/lis/fee/item/getFeeItemListByRptGroup';
  let obj = {
    params: {
      keyWords: searchForm.groupSearchValue,
      orgId: searchForm.orgId,
      rptGroup: searchGroupForm.rptGroup
    }
  };
  proxy.$http
    .get(url, obj)
    .then((res: any) => {
      if (res && res.data && res.data.length > 0) {
        feeItemList.push(...res.data);
        if (feeItemList.length > 0) {
          const kn = feeItemList.find((k) => k.id == selevctFeeItemRow.id);
          if (isEmpty(kn)) {
            grouprowClick({ row: feeItemList[0] });
          } else {
            grouprowClick({ row: kn });
          }
        } else {
          selevctFeeItemRow.id = '';
          feeitemVsItemdictList.length = 0;
        }
      } else {
        selevctFeeItemRow.id = '';
        feeitemVsItemdictList.length = 0;
      }
      feeItemShowLoading.value = false;
    })
    .catch((err: any) => {
      proxy.$alert(err, '提示');
      feeItemShowLoading.value = false;
    });
}

// 获取报告项目列表
function findDictItemByFeeItemId(row: any) {
  itemDictList.length = 0;
  showLoading.value = true;
  const url = '/api/LabFeeitemVsItemdict/findDictItemByFeeItemId';
  let obj = {
    params: {
      keyWords: searchValue.value,
      feeCode: row.feeCode,
      rptGroup: searchGroupForm.rptGroup,
      pageIndex: page.currentPage,
      pageSize: page.pageSize
    }
  };
  proxy.$http
    .get(url, obj)
    .then((res: any) => {
      if (res.data && res.data.records.length > 0) {
        itemDictList.push(...res.data.records);
        page.totalResult = res.data.total;
      } else {
        page.totalResult = 0;
      }
      showLoading.value = false;
    })
    .catch((err: any) => {
      proxy.$alert(err, '提示');
      showLoading.value = false;
    });
}
function handleSizeChange({ type, currentPage, pageSize }) {
  if (type === 'size') {
    page.currentPage = 1;
  } else {
    page.currentPage = currentPage;
  }
  page.pageSize = pageSize;
  findDictItemByFeeItemId(selevctFeeItemRow);
}

// 点击当前行// 行点击事件
function grouprowClick({ row }: any) {
  (proxy.$refs.labFeeItemTable as any).setCurrentRow(row);
  selevctFeeItemRow = row;
  proxy.$nextTick(() => {
    setTimeout(() => {
      (proxy.$refs.labFeeItemTable as any).scrollToRow(row);
    }, 150);
  });
  findItemDictList();
  page.currentPage = 1;
  findDictItemByFeeItemId(row);
}

// 获取中间的报告单元信息
function findItemDictList() {
  feeitemVsItemdictList.length = 0;
  const url = '/api/LabFeeitemVsItemdict/findItemDictListByFeeId';
  const data = {
    params: {
      feeCode: selevctFeeItemRow.feeCode,
      rptGroup: searchGroupForm.rptGroup
    }
  };
  proxy.$http
    .get(url, data)
    .then((res: any) => {
      feeitemVsItemdictList.push(...res.data);
    })
    .catch((err: any) => {
      proxy.$alert(err, '提示');
    });
}
//双击右侧列表
function itemDictRowClick({ row }: any) {
  if (isEmpty(selevctFeeItemRow.id)) {
    VxeMessage('请选择申请项目', VxeNotifyType.error);
    return;
  }
  const url = '/api/LabFeeitemVsItemdict/addFeeItemVsItemDict';
  let labFeeitemVsItemDict = {
    feeCode: selevctFeeItemRow.feeCode,
    itemNo: row.itemNo,
    rptGroup: searchGroupForm.rptGroup,
    seq: row.seq
  };
  proxy.$http
    .post(url, labFeeitemVsItemDict)
    .then((res: any) => {
      getFeeItemList();
    })
    .catch((err: any) => {
      proxy.$alert(err, '提示');
    });
}

// 双击中间列表删除数据
function deleteFeeitemVsItemdictList({ row }: any) {
  const url = '/api/LabFeeitemVsItemdict/deleteFeeitemVsItemdict';
  proxy.$http
    .post(url, {
      id: row.feeVSItemDictId,
      name: row.itemName
    })
    .then((res: any) => {
      getFeeItemList();
      VxeMessage(res.status.msg, VxeNotifyType.success);
    })
    .catch((err: any) => {
      VxeMessage(err, VxeNotifyType.error);
    });
}

// 下拉报告单元获取报告单元id
function getSelectedId(selectedRadioId, selectedName) {
  GetRptGroupOptions(selectedRadioId.value);
  searchGroupForm.rptGroup = selectedRadioId.value;
  getFeeItemList();
  getInstrList();
  copyfeeVsDictList.length = 0;
}

let copyfeeVsDictList: any = reactive([]);

function copyFeeitemVsItemDict() {
  if (feeitemVsItemdictList.length > 0) {
    copyfeeVsDictList.length = 0;
    VxeMessage('已复制到剪贴板', VxeNotifyType.success);
    copyfeeVsDictList.push(...feeitemVsItemdictList);
  } else {
    VxeMessage('没有要复制的项目', VxeNotifyType.error);
  }
}
function pasteFeeitemVsItemDict() {
  for (let copyfeeVsDict of copyfeeVsDictList) {
    const i = feeitemVsItemdictList.findIndex((a: any) => a.itemNo == copyfeeVsDict.itemNo);
    if (i <= -1) {
      let record: any = {
        feeCode: selevctFeeItemRow.feeCode,
        itemNo: copyfeeVsDict.itemNo,
        itemNa: copyfeeVsDict.itemNa,
        rptGroup: searchGroupForm.rptGroup,
        seq: copyfeeVsDict.seq,
        isOptional: copyfeeVsDict.isOptional
      };
      feeitemVsItemdictList.push(record);
    }
  }
}

function saveFeeitemVsItemDictList() {
  if (feeitemVsItemdictList.length > 0) {
    const url = '/api/LabFeeitemVsItemdict/saveBatchFeeItemVsItemDict';
    const obj: any = {};
    obj.feeitemVsItemDictList = feeitemVsItemdictList;
    proxy.$http
      .post(url, obj)
      .then((res: any) => {
        getFeeItemList();
      })
      .catch((err: any) => {
        proxy.$alert(err, '提示');
      });
  } else {
    VxeMessage('没有要复制的项目', VxeNotifyType.error);
  }
}
</script>
<style lang="scss" scoped>
#applyVSReport {
  height: 100%;

  .bodyContent {
    height: calc(100% - 60px);

    .area {
      background-color: $base-white;

      // 附加按钮间距
      .button-blue,
      .button-red {
        margin: 5px 0 5px 5px;
      }

      .leftTable {
        height: calc(100% - 40px);
      }

      .rightTable {
        height: calc(100% - 40px - 32px);
      }

      // 右侧基本信息表单
      .baseForm {
        .el-row {
          margin-left: 0 !important;
          margin-right: 0 !important;
        }

        .form-footer {
          :deep(.el-form-item__content) {
            margin-left: 120px !important;
          }
        }

        .el-form-item--large {
          margin-bottom: 10px;
        }

        .el-radio {
          margin-right: 20px;
        }
      }
    }
  }
}
</style>
